/**
 * 消息相关API接口
 */

import { request,streamRequest } from '@/utils/request';
import axios  from 'axios';

// 类型定义
export interface Message {
  content: string;
  reasonContent: string;
  type?: string;
  conversationId: string;
  user_id?: string;
  role: 'USER' | 'ASSISTANT';
}

export interface MessageDTO extends Message {
  id: string;
  createTime: string;
  updateTime: string | null;
}

export interface MessageRequestDTO {
  conversationId: string;
  content: string;
  reasonContent?: string;
  agentId?: number;
}

export interface ChatResult {
  messageId: string;
  conversationId: string;
  content: string;
  reasoningContent: string;
  toolCalls: ToolCallResult[];
  usage: Usage;
  complete: boolean;
}

export interface ToolCallResult {
  id: string;
  type: string;
  function: ToolFunctionCall;
}

export interface ToolFunctionCall {
  name: string;
  arguments: string;
}

export interface Usage {
  promptTokens: string;
  completionTokens: string;
  totalTokens: string;
}

// 获取消息列表
export async function getAllMessages(): Promise<MessageDTO[]> {
  return request.get('/api/messages/list');
}

// 获取单个消息
export async function getMessageById(id: string): Promise<MessageDTO> {
  return request.get('/api/messages/get', { params: { id } });
}

// 创建消息
export async function createMessage(data: Message): Promise<MessageDTO> {
  return request.post('/api/messages/create', data);
}

// 更新消息
export async function updateMessage(id: string, data: Message): Promise<MessageDTO> {
  return request.put(`/api/messages/update?id=${id}`, data);
}

// 处理用户消息 - 普通响应
export async function chat(data: MessageRequestDTO): Promise<MessageDTO> {
  return request.post('/api/messages/chat', data);
}

// 处理用户消息 - 流式响应
export async function chatStream(data: MessageRequestDTO): Promise<any> {
  const stream = await streamRequest.post('/api/messages/chat/stream', data, {
    headers: {
      Accept: 'text/event-stream', // 指定接受 Event Stream 格式
    },
    responseType: 'stream', // 指定响应类型为流
  });
  console.log('chatStream ....', stream);
  return stream as any;
}

// 获取对话消息列表
export async function getMessagesByConversation(conversationId: string): Promise<MessageDTO[]> {
  return request.get('/api/messages/conversation', { params: { conversationId } });
}

// 删除消息
export async function deleteMessage(id: string): Promise<void> {
  return request.delete('/api/messages/delete', { params: { id } });
}